<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>RSA Util Test</title>
    <script src="/packages/libs/ofa/ofa.js" type="module"></script>
  </head>
  <body>
    <script src="/sw/register.js" type="module"></script>
    <script type="module">
      import { test } from "/ok-test/main.js";
      import {
        generateRSAKeyPair,
        encryptMessage,
        decryptMessage,
      } from "/packages/crypto/crypto-rsa.js";

      await test("RSA Key Generation Test", async () => {
        const { publicKey, privateKey } = await generateRSAKeyPair();

        return {
          assert: !!publicKey && !!privateKey,
          content: {
            message: "RSA密钥对生成成功",
            publicKeyLength: publicKey.length,
            privateKeyLength: privateKey.length,
          },
        };
      });

      await test("RSA Encryption and Decryption Test", async () => {
        const { publicKey, privateKey } = await generateRSAKeyPair();
        const testMessage = "Hello, RSA Test!";

        // 加密消息
        const encrypted = await encryptMessage(publicKey, testMessage);

        // 解密消息
        const decrypted = await decryptMessage(privateKey, encrypted);

        return {
          assert: decrypted === testMessage,
          content: {
            message: "RSA加解密测试成功",
            originalMessage: testMessage,
            encryptedLength: encrypted.length,
            decryptedMessage: decrypted,
            matched: decrypted === testMessage,
          },
        };
      });

      await test("RSA Invalid Input Test", async () => {
        const { publicKey, privateKey } = await generateRSAKeyPair();

        // let encryptError = null;
        let decryptError = null;

        // try {
        //   await encryptMessage(publicKey, null);
        // } catch (error) {
        //   encryptError = error.message;
        // }

        try {
          await decryptMessage(privateKey, "invalid-encrypted-data");
        } catch (error) {
          decryptError = error.message;
        }

        return {
          // assert: !!encryptError && !!decryptError,
          assert: !!decryptError,
          content: {
            message: "RSA无效输入测试成功",
            // encryptError,
            decryptError,
          },
        };
      });
    </script>
  </body>
</html>
